import { ossApi } from '@/api'
import serviceUtil from '@/utils/service'
import storeUtil from '@/utils/store'
import OSS from 'ali-oss'

const ossUploadUtil = {}
/**
 * @Author tangyuhui
 * @Description
 * @Date 2020-02-06 21:44:53 Thursday
 */
ossUploadUtil.uploadToOss = function(params) {
  return new Promise(async(resolve, reject) => {
    try {
      const bizKey = (params && params.bizKey) || 'MARTECT'
      const folderName = (params && params.folderName) || '/'
      // 获取本地ossSts
      const ossSts = storeUtil.getExpireStorage('ossSts' + bizKey)
      let ret = null
      if (ossSts) {
        ret = ossSts
      } else {
        ret = await ossApi.getOssSts(bizKey).then(serviceUtil.filterBmsBackendData)
      }
      if (!ret) {
        reject('获取上传凭证失败!')
      } else {
        // 存储
        storeUtil.setExpireStorage('ossSts' + bizKey, ret, 0.0034) // 5分钟
        const client = new OSS.Wrapper({
          accessKeyId: ret.accessKeyId,
          accessKeySecret: ret.accessKeySecret,
          bucket: ret.bucket,
          stsToken: ret.securityToken,
          endpoint: ret.endpoint
        })
        const file = params.file
        const fileName = params.fileName
        ret = await client.multipartUpload(folderName + '/' + fileName, file, {
          async progress(p) {
            const e = {}
            e.percent = p * 100
          },
          headers: {
            'Cache-Control': 'no-cache',
            'x-oss-object-acl': 'public-read'
          }
        })
        if (ret && ret.res && ret.res.statusCode === 200) {
          console.log(ret)
          resolve(ret)
        } else {
          reject('上传文件失败，请重试!')
        }
      }
    } catch (e) {
      console.log(e)
      reject(e)
    }
  })
}
export default ossUploadUtil
